﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Threading;


/// <summary>
/// 数据接收分发类
/// </summary>

public class DataListener
{
    // 数据
    public UdpClient server;
    public bool running;  
    Thread thread;
    public DataListener()
    {
        running = true;
    }
    
    /// <summary>
    ///  接收
    /// </summary>
    public void rec()
    {
        if (null != thread)
        {
            thread.Abort();
            thread = null;
            server = null;
        }
        thread = new Thread(rec_thread);
        thread.IsBackground = true;
        thread.Start();
    }
    // 接收数据线程
    public void rec_thread()
    {
        try
        {
            server = new UdpClient(NetPara.PORT_LOCAL);    //监听端口  
        }
        catch (SocketException err)
        {
            MessageBox.Show(err.Message, "端口被占用了");
            return;
        }
        IPEndPoint receivepoint = new IPEndPoint(IPAddress.Any, NetPara.PORT_LOCAL);
        while (running)
        {
            byte[] recbyte = server.Receive(ref receivepoint);  //堵塞接受
            string strData = Encoding.UTF8.GetString(recbyte);  //接受到数据
            if (NetPara.IS_IMPLEMENTORDER)   //先判断是否需要处理消息
            {
                DataHandler DataHandler = new DataHandler(strData, receivepoint);
            }
        }
    }
    // 关闭接收线程
    public void stop()
    {
        thread.Abort();
        server.Close();
    }
   
}